import sys

def calculate_cdf(flow_sizes):
    # 对流大小排序
    sorted_sizes = sorted(flow_sizes)
    n = len(sorted_sizes)
    
    # 计算CDF
    # 对于第 i 个流(size)的CDF = (i+1)/n * 100%
    cdf_data = []
    for i, size in enumerate(sorted_sizes):
        cdf_val = (i + 1) / n * 100
        cdf_data.append((size, cdf_val))
    return cdf_data

def print_cdf(cdf_results, segments=None):
    """
    打印CDF结果。
    如果segments为None或小于1，打印所有点。
    否则，分成指定数量segments的档位打印结果。
    """
    n = len(cdf_results)
    if segments is None or segments < 1:
        # 打印所有点
        for size, cdf_val in cdf_results:
            print(f"{size}\t{cdf_val:.2f}")
    else:
        # 打印分档点
        # 示例：segments=10，则CDF分为0%,10%,20%,...100%
        for i in range(segments + 1):
            fraction = i / segments
            index = int(fraction * (n - 1))  # 对应的CDF索引
            size, _ = cdf_results[index]
            cdf_val = fraction * 100
            print(f"{size}\t{cdf_val:.2f}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: python verify_cdf.py flow_data.txt [--segments N]")
        sys.exit(1)
    
    filename = None
    segments = None

    # 简单解析参数
    for arg in sys.argv[1:]:
        if arg.startswith("--segments"):
            # 例如: --segments=10
            parts = arg.split("=")
            if len(parts) == 2 and parts[1].isdigit():
                segments = int(parts[1])
        else:
            filename = arg
    
    if filename is None:
        print("请指定输入文件")
        sys.exit(1)

    flow_sizes = []
    with open(filename, 'r') as f:
        lines = f.readlines()
    
    # 第一行是流的数量
    total_flows = int(lines[0].strip())
    # 从第二行开始，每行解析
    for line in lines[1:]:
        fields = line.strip().split()
        if len(fields) < 5:
            continue
        flow_size = int(fields[4])
        flow_sizes.append(flow_size)
    
    # 校验数量是否一致（可选）
    if len(flow_sizes) != total_flows:
        print(f"警告: 实际读取的流数量({len(flow_sizes)})与文件头指定的数量({total_flows})不一致。")
    
    # 计算CDF
    cdf_results = calculate_cdf(flow_sizes)

    # 打印CDF，根据segments输出相应的点
    print_cdf(cdf_results, segments=segments)
